package com.ypaco.ajax.client;
import com.ypaco.ajax.client.RemoteXMLRequestCallback;
import com.google.gwt.http.client.*;
import com.google.gwt.xml.client.*;



public class RemoteXML {
	
	RequestBuilder builder;
	
	public RemoteXML(String url,String method){
		builder=new RequestBuilder((method.compareTo("POST")==0)?RequestBuilder.POST:RequestBuilder.GET,URL.encode(url));
		if (method.compareTo("POST")==0)
			builder.setHeader("Content-Type", "application/x-www-form-urlencoded");
	}
	public RemoteXML(String url){
		builder=new RequestBuilder(RequestBuilder.GET,URL.encode(url));
	}
	
	public void request(String data,final RemoteXMLRequestCallback callback){
		try{
			builder.sendRequest(data, new RequestCallback(){
				public void onError(Request request, Throwable exception){
						callback.onFailure(exception);
				}

			    public void onResponseReceived(Request request, Response response) {
			      if (200 == response.getStatusCode()) {
			    	  try
			    	  {
			    		  Document doc=XMLParser.parse(response.getText());
			    		  callback.onSuccess(doc);
			    	  }catch(Throwable ex){
			    		  callback.onFailure(ex);
			    	  }
			      } else {
						callback.onFailure(new BadStatusCodeException(response.getStatusCode()));
			      }
			      }
			});
		}catch(Exception ex){
			callback.onFailure(ex);
		}
	}

}
